<template>
  <el-card>
    <el-form label-width="120px" :model="skuInfo" :rules="skuFormRules" ref="skuFormRef">
      <el-form-item label="SPU名称">
        <span>{{currentSpuInfo.spuName}}</span>
      </el-form-item>
      <el-form-item label="SKU名称" prop="skuName">
        <el-input v-model="skuInfo.skuName" placeholder="SKU名称"></el-input>
      </el-form-item>
      <el-form-item label="价格(元)" prop="price">
        <el-input v-model="skuInfo.price" type="number" :min="0" :max="100"></el-input>
      </el-form-item>
      <el-form-item label="重量(千克)" prop="weight">
        <el-input v-model="skuInfo.weight" type="number" :min="0" :max="100"></el-input>
      </el-form-item>
      <el-form-item label="规格描述" prop="skuDesc">
        <el-input type="textarea" placeholder="请输入sku描述" v-model="skuInfo.skuDesc" rows="4"></el-input>
      </el-form-item>

      <el-form-item label="平台属性" prop="skuAttrValueList">
        <el-row :gutter="10">
          <el-col v-for="(attr,index) in attrList" :key="attr.id" :xs="24" :sm="12" :md="8" :lg="8" :xl="6">
            <el-form-item style="margin-bottom:10px" :label="attr.attrName">
              <el-select v-model="skuInfo.skuAttrValueList[index]" placeholder="请选择" @change="toClearAttrValueRules">
                <el-option v-for="attrValue in attr.attrValueList" :key="attrValue.id" :label="attrValue.valueName" :value="`${attr.id}:${attr.attrName}:${attrValue.id}:${attrValue.valueName}`" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item label="销售属性" 
      prop="skuSaleAttrValueList">
        <el-row :gutter="10">
          <el-col v-for="(saleAttr,index) in spuSaleAttrList" :key="saleAttr.id" :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
            <el-form-item :label="saleAttr.saleAttrName">
              <el-select v-model="skuInfo.skuSaleAttrValueList[index]" @change="toClearSaleAttrRules">
                <el-option v-for="saleAttrValue in saleAttr.spuSaleAttrValueList" :label="saleAttrValue.saleAttrValueName" :value="`${saleAttr.id}:${saleAttr.saleAttrName}:${saleAttrValue.id}:${saleAttrValue.saleAttrValueName}`" :key="saleAttrValue.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="图片列表" prop="skuImageList">
        <el-table border :data="spuImageList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" align="center" width="80"></el-table-column>
          <el-table-column label="图片">
            <template v-slot="{row}">
              <el-image style="width: 100px; height: 100px" :src="row.imgUrl" fit="fill" />
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="imgName"></el-table-column>
          <el-table-column label="操作">
            <template v-slot="{row}">
              <el-button type="primary" v-if="row.isDefault==='0'" @click="toSetDefaultImg(row)">设置默认图片</el-button>
              <el-button type="success" v-else disabled>默认图片</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-button type="primary" style="margin-left:120px" @click="submitSkuForm(skuFormRef)">保存</el-button>
      <el-button>取消</el-button>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name:'SkuForm'
}
</script>

<script lang="ts" setup>
import { ref,onMounted,reactive } from 'vue'
import {reqGetSpuImageListData,reqGetSpuSaleAttrListData } from '@/api/product/spu'
import {reqGetAttrListData} from '@/api/product/attr'
import { useCategoryListStore } from '@/stores/categoryList';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { reqSaveSkuInfo } from '@/api/product/sku';
import { ShowStatus } from '../types';


const categoryStore = useCategoryListStore()
const props = defineProps(['currentSpuInfo'])
const emits = defineEmits(['setShowStatus'])

//定义数据
const spuImageList = ref([]) //图片列表
const spuSaleAttrList = ref([])  // spu 属性列表
const attrList = ref([])  //平台属性列表
const skuFormRef = ref<FormInstance>()
const skuInfo = reactive({
  skuName: '', // sku名称
  spuId: -1, // spu的id
  tmId: 0, // 品牌Id
  weight: 1, // 重量
  skuDefaultImg: '', // 设置的默认图片链接
  skuDesc: '', // sku描述
  category3Id: 0, // 分类的3Id
  price: 1, // 价格
  // 平台属性
  skuAttrValueList: [],
  // 图片列表
  skuImageList: [],
  // 销售属性数组
  skuSaleAttrValueList: []
})

//自定义校验规则
//rule：校验规则 ，value：待校验的数据 callback： 回调函数
const skuAttrValueListRule = (rule:any, value:any,callback:any)=>{
  if(!value.length){
    callback('至少选择一个平台属性')
    return
  }
  //通过校验
  callback()
}

const skuSaleAttrValueListRule = (rule:any, value:any,callback:any)=>{
  if(!value.length){
    callback('至少选择一个销售属性')
    return
  }
  //通过校验
  callback()
}

const skuImageListRule = (rule:any, value:any,callback:any)=>{
  if (value.length < 3) {
    return callback('请至少选择三张图片...');
  }

  callback();
}

//书写校验规则
const skuFormRules = reactive<FormRules>({
  skuName:[
    {required: true, message: '请填写sku名称',trigger:'blur'},
    {min: 2, max: 10, message: '长度应该在2-10个字符之间',trigger:'blur'}
  ],
  price:[
    {required: true, message: '请设置一个价格',trigger:'blur'},
  ],
  weight:[
    {required: true, message: '请添加一个重量',trigger:'change'},
  ],
  skuDesc:[
     {required: true, message: '请输入sku描述',trigger:'blur'},
  ],
  skuImageList:[
    {required: true, validator: skuImageListRule,trigger:'change'},
  ],
  skuAttrValueList:[
    {required: true, validator:  skuAttrValueListRule,trigger:'change'},
  ],
  skuSaleAttrValueList:[
    {required: true, validator:  skuSaleAttrValueListRule,trigger:'change'},
  ]
})


//一挂载就要请求获取数据
onMounted(async ()=>{
 try{

  const { id: spuId } = props.currentSpuInfo
  const{ category1Id,category2Id,category3Id } = categoryStore
  const [ resSpuImageList,resSpuSaleAttrList,resAttrList ] = await Promise.allSettled([reqGetSpuImageListData(spuId),reqGetSpuSaleAttrListData(spuId),reqGetAttrListData({category1Id,category2Id,category3Id})])

  if(resSpuImageList.status ==="fulfilled"){
    spuImageList.value = resSpuImageList.value.map(item=>{
      return{
        ...item,
        isDefault:'0'
      }
    })
  }
  if(resSpuSaleAttrList.status === 'fulfilled'){
    spuSaleAttrList.value = resSpuSaleAttrList.value
  }
  if(resAttrList.status==='fulfilled'){
    attrList.value = resAttrList.value
  }

 }catch(error){
   console.log(error);
   
 }
});

//设置默认图片
const toSetDefaultImg =(row)=>{
  spuImageList.value.forEach(item=>{
    item.isDefault ='0'
  })
  row.isDefault = '1'
  //收集当前默认图片的链接
  skuInfo.skuDefaultImg = row.imgUrl
}

//获取所选图片地址
const handleSelectionChange = (val)=>{
   if(val.length >=3){
    skuFormRef.value?.clearValidate(['skuImageList'])
    skuInfo.skuImageList = val
   }
}

//清空平台属性校验规则
const toClearAttrValueRules = ()=>{
  skuFormRef.value?.clearValidate(['skuAttrValueList'])
}

//清空销售属性校验规则
const toClearSaleAttrRules = ()=>{
  skuFormRef.value?.clearValidate(['skuSaleAttrValueList'])
}

//单击保存,添加skuInfo数据
const submitSkuForm=(formEl: FormInstance | undefined)=>{
  if(!formEl) return
  formEl.validate(async valid=>{
    if(valid){
      //处理平台属性
      skuInfo.skuAttrValueList = skuInfo.skuAttrValueList.filter(Boolean).map(item=>{
        const [ attrId, attrName, valueId, valueName] =item.split(':')
        return{
          attrId,
          attrName,
          valueId,
          valueName
        }
      })
      //处理销售属性
      skuInfo.skuSaleAttrValueList = skuInfo.skuSaleAttrValueList.filter(Boolean).map(item=>{
        const [saleAttrId, saleAttrName,saleAttrValueId,saleAttrValueName] = item.split(':')
        return{
          saleAttrId,
          saleAttrName,
          saleAttrValueId,
          saleAttrValueName
        }
      })
      //检验默认图片是否在选择图片中
      if(!skuInfo.skuImageList.find(item=>item.isDefault==='1')){
        ElMessage.warning('请在列表中选择一张默认图片')
        return
      }
      skuInfo.category3Id = categoryStore.category3Id
      skuInfo.spuId = props.currentSpuInfo.id
      skuInfo.tmId = props.currentSpuInfo.tmId

      await reqSaveSkuInfo(skuInfo)

      ElMessage.success('添加skuInfo数据成功')
      //跳转到spu页面
      emits('setShowStatus',ShowStatus.SPU_LIST)
    } else{
      console.log('error submit!');
      return false
    }
  })
}

</script>
<style>

</style>